package com.njupt.DoublePoint;

import java.util.ArrayList;
import java.util.List;

/**
 * 142. 环形链表 II
 * 给定一个链表的头节点  head ，返回链表开始入环的第一个节点。 如果链表无环，则返回 null。
 */
public class DetectCycle {

    public ListNode detectCycle(ListNode head) {
        ListNode pre = head;
        ListNode rear = head;

        ListNode lastNode = head;
        while(lastNode.next != null) lastNode = lastNode.next;


        while(pre != null){

            while (rear != null){
                if(rear.next == pre){
                    return  pre;
                }
                rear = rear.next;
            }
            pre = pre.next;
            rear = pre;
        }
        return null;
    }

    public ListNode detectCycle1(ListNode head){
        List<ListNode> listNodes = new ArrayList<>();
        ListNode p = head;
        while(p != null){
            listNodes.add(p);
            if(listNodes.contains(p.next)){
                return p.next;
            }
            p = p.next;
        }
        return null;
    }

    public static void main(String[] args) {

        ListNode head = new ListNode(3);
        ListNode node1 = new ListNode(2);
        ListNode node2 = new ListNode(0);
        ListNode node3 = new ListNode(-4);
        head.next = node1;
        node1.next = node2;
        node2.next = node3;
        node3.next = node1;

        DetectCycle test = new DetectCycle();
        System.out.println(test.detectCycle1(head).val);


    }
}
